import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

// 检查是否在浏览器环境中
const isBrowser = typeof window !== 'undefined';

let db: any = null;

// 只在Node.js环境中初始化数据库
if (!isBrowser) {
  try {
    db = require('../database/db').default;
  } catch (error) {
    console.log('数据库未初始化，使用模拟数据');
  }
}

export interface Material {
  id: string;
  name: string;
  type: 'image' | 'video' | 'audio' | 'text' | 'markdown';
  category: string;
  size: number;
  path: string;
  tags: string[];
  uploadTime: string;
  createdAt: string;
}

interface MaterialState {
  materials: Material[];
  loading: boolean;
  error: string | null;
  
  // Actions
  fetchMaterials: () => Promise<void>;
  addMaterial: (file: File, category: string, tags: string[]) => Promise<void>;
  deleteMaterial: (id: string) => Promise<void>;
  updateMaterial: (id: string, updates: Partial<Material>) => Promise<void>;
  getMaterialsByType: (type: Material['type']) => Material[];
  getMaterialsByCategory: (category: string) => Material[];
}

// 文件类型映射
const FILE_TYPE_MAP: Record<string, Material['type']> = {
  'jpg': 'image',
  'jpeg': 'image',
  'png': 'image',
  'gif': 'image',
  'webp': 'image',
  'bmp': 'image',
  'svg': 'image',
  'mp4': 'video',
  'avi': 'video',
  'mov': 'video',
  'wmv': 'video',
  'flv': 'video',
  'mkv': 'video',
  'mp3': 'audio',
  'wav': 'audio',
  'flac': 'audio',
  'aac': 'audio',
  'ogg': 'audio',
  'txt': 'text',
  'md': 'markdown',
  'doc': 'text',
  'docx': 'text',
  'pdf': 'text'
};

export const useMaterialStore = create<MaterialState>()(
  devtools(
    (set, get) => ({
      materials: [],
      loading: false,
      error: null,

      fetchMaterials: async () => {
        set({ loading: true, error: null });
        try {
          if (isBrowser || !db) {
            // 浏览器环境或数据库未初始化，使用模拟数据
            const mockMaterials: Material[] = [
              {
                id: '1',
                name: 'product_image.jpg',
                type: 'image',
                category: 'image',
                size: 1024000,
                path: '/storage/image/product_image.jpg',
                tags: ['产品', '图片'],
                uploadTime: '2024-01-15 14:30:00',
                createdAt: '2024-01-15'
              },
              {
                id: '2',
                name: 'video_demo.mp4',
                type: 'video',
                category: 'video',
                size: 5120000,
                path: '/storage/video/video_demo.mp4',
                tags: ['演示', '视频'],
                uploadTime: '2024-01-14 10:20:00',
                createdAt: '2024-01-14'
              }
            ];
            set({ materials: mockMaterials, loading: false });
          } else {
            const stmt = db.prepare('SELECT * FROM materials ORDER BY createdAt DESC');
            const materials = stmt.all() as any[];
            // 解析tags字符串为数组
            const materialsWithTags = materials.map(material => ({
              ...material,
              tags: material.tags ? JSON.parse(material.tags) as string[] : []
            })) as Material[];
            set({ materials: materialsWithTags, loading: false });
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      addMaterial: async (file, category, tags) => {
        set({ loading: true, error: null });
        try {
          const id = Date.now().toString();
          const now = new Date().toISOString();
          
          // 获取文件扩展名
          const ext = file.name.split('.').pop()?.toLowerCase() || '';
          const type = FILE_TYPE_MAP[ext] || 'text';
          
          const newMaterial: Material = {
            id,
            name: file.name,
            type,
            category,
            size: file.size,
            path: `/storage/${type}/${file.name}`,
            tags,
            uploadTime: now,
            createdAt: now,
          };

          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              materials: [newMaterial, ...state.materials],
              loading: false
            }));
          } else {
            const stmt = db.prepare(`
              INSERT INTO materials (id, name, type, category, size, path, tags, uploadTime, createdAt)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            `);
            stmt.run(
              newMaterial.id,
              newMaterial.name,
              newMaterial.type,
              newMaterial.category,
              newMaterial.size,
              newMaterial.path,
              JSON.stringify(newMaterial.tags),
              newMaterial.uploadTime,
              newMaterial.createdAt
            );

            set(state => ({
              materials: [newMaterial, ...state.materials],
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      deleteMaterial: async (id) => {
        set({ loading: true, error: null });
        try {
          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              materials: state.materials.filter(material => material.id !== id),
              loading: false
            }));
          } else {
            const material = get().materials.find(m => m.id === id);
            if (material && require('fs').existsSync(material.path)) {
              require('fs').unlinkSync(material.path);
            }

            const stmt = db.prepare('DELETE FROM materials WHERE id = ?');
            stmt.run(id);

            set(state => ({
              materials: state.materials.filter(material => material.id !== id),
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      updateMaterial: async (id, updates) => {
        set({ loading: true, error: null });
        try {
          const now = new Date().toISOString();
          
          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              materials: state.materials.map(material =>
                material.id === id ? { ...material, ...updates } : material
              ),
              loading: false
            }));
          } else {
            const updateFields = Object.keys(updates)
              .filter(key => key !== 'id')
              .map(key => `${key} = ?`)
              .join(', ');

            const stmt = db.prepare(`
              UPDATE materials 
              SET ${updateFields}
              WHERE id = ?
            `);

            const values = [...Object.values(updates), id];
            stmt.run(...values);

            set(state => ({
              materials: state.materials.map(material =>
                material.id === id ? { ...material, ...updates } : material
              ),
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      getMaterialsByType: (type) => {
        return get().materials.filter(material => material.type === type);
      },

      getMaterialsByCategory: (category) => {
        return get().materials.filter(material => material.category === category);
      },
    }),
    {
      name: 'material-store',
    }
  )
); 